package com.parachutes.aspgateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;

@Component
public class LoggingFilter implements GatewayFilter {

    private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 记录请求的信息
        String requestPath = exchange.getRequest().getURI().getPath();
        String method = exchange.getRequest().getMethodValue();
        String requestHeaders = exchange.getRequest().getHeaders().toString();

        logger.info("Incoming request: method={} path={} headers={}", method, requestPath, requestHeaders);

        // 继续传递请求
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 记录响应的日志
            String responseStatus = String.valueOf(exchange.getResponse().getStatusCode());
            logger.info("Outgoing response: status={}", responseStatus);
        }));
    }
}
